const {db} = require("../util/util")

const login = (mnemonic) => {//登陆
  const sql = "select * from user where mnemonic = ?";
  return db.execute(sql,[mnemonic]).then((data) => {
    return data[0][0];
  })
}

const register = (name,address,mnemonic,public_key,private_key,create_time,last_login_time) => {//注册
  const sql = "insert into user (name,address,mnemonic,public_key,private_key,create_time,last_login_time) values(?,?,?,?,?,?,?)";
  return db.execute(sql,[name,address,mnemonic,public_key,private_key,create_time,last_login_time]).then((data) => {
    return data[0].insertId;
  });
}

const updateUser = (id,name) => {//更新用户姓名
  const sql = "update user set name = ? where id = ?";
  return db.execute(sql,[name,id]).then((data) => {
    return data[0].affectedRows;
  })
}

const deleteUser = (id) => {//删除用户
  sql = "delete from user where id = ?";
  return db.execute(sql,[id]).then((data) => {
    return data[0].affectedRows;
  })
}

const updateLastLoginTime = (id,time) => {//更新上一次登陆时间
  sql = "update user set last_login_time = ? where id = ?";
  return db.execute(sql,[time,id]);
}

const getUserById = (id) => {//根据id获取用户信息
  sql = "select * from user where id = ?";
  return db.execute(sql,[id]).then((data) => {
    return data[0][0];
  });
}

const getUserByName = (name) => {//根据用户名查询用户 判断用户名是否重复
  sql = "select * from user where name = ?";
  return db.execute(sql,[name]).then((data) => {
    return data[0][0];
  })
} 

const getUserIdByAddress = (address) => {//根据用户地址查看用户id
  sql = "select id from user where address = ?";
  return db.execute(sql,[address]).then((data) => {
    return data[0][0].id;
  })
}

const getUsers = () => {//获取用户列表 。。。/
  const sql = "select * from user";
  return db.execute(sql).then((data) => {
    return data[0]; //获取user列表
  })
}

// register(["ZQJ","dada","mnemonic","public_key","private_key",new Date(),new Date()]).then((data)=>{
//   console.log(data[0].insertId);
// })


module.exports = {login, register,  updateUser, deleteUser, updateLastLoginTime, getUserById, getUserByName, getUserIdByAddress, getUsers};